package pl.edu.mimuw.irs.rcp.controller.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISources;
import org.eclipse.ui.handlers.HandlerUtil;

import pl.edu.mimuw.irs.rcp.util.Logger;
import pl.edu.mimuw.irs.rcp.util.MessageCode;
import pl.edu.mimuw.irs.rcp.util.UITexts;

public class DeleteProjectHandler extends AbstractHandler {

	// *** Attributes
	
	// *** Methods
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Object selection = HandlerUtil.getVariable(event, ISources.ACTIVE_CURRENT_SELECTION_NAME);
		if (selection instanceof StructuredSelection) {
			StructuredSelection structuredSelection = (StructuredSelection) selection;
			for (Object object : structuredSelection.toArray()) {
				if (object instanceof IProject) {
					IProject project = (IProject) object;
					MessageBox msgBox = new MessageBox(getShell(), SWT.YES | SWT.NO | SWT.ICON_QUESTION);
					msgBox.setText(UITexts.get(MessageCode.QUESTION_TITLE));
					msgBox.setMessage(UITexts.get(MessageCode.PROJECT_DELETE_QUESTION) + "\n" + project.getName());
					
					switch (msgBox.open()) {
					case SWT.YES:
						try {
							project.delete(true, new NullProgressMonitor());
						} catch (CoreException e) {
							Logger.handle(MessageCode.PROJECT_DELETE_PROBLEM, e, project.getName());
						}
						break;
					}
				}
			}
		}
		
		return null;
	}
	
	private static Shell getShell() {
		Display display = Display.getCurrent();
		Shell shell = display.getActiveShell();
		Shell[] shells = display.getShells();
		if (shells.length > 0) shell = shells[shells.length - 1];
		return shell;
	}
}
